package utils

import (
	"context"
	"duoke/utils/gmd5"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"io/ioutil"
	"net/url"
	"strings"
)

var kd100Flags = map[string]string{
	"安能快递":    "ane66",
	"德邦物流":    "debangwuliu",
	"德邦快递":    "debangkuaidi",
	"EMS":     "ems",
	"国通快递":    "guotongkuaidi",
	"百世快递":    "huitongkuaidi",
	"京东物流":    "jd",
	"跨越速运":    "kuayue",
	"品骏快递":    "pjbest",
	"申通快递":    "shentong",
	"顺丰速运":    "shunfeng",
	"速尔快递":    "suer",
	"信丰物流":    "xinfengwuliu",
	"优速物流":    "youshuwuliu",
	"邮政快递包裹":  "youzhengguonei",
	"圆通速递":    "yuantong",
	"圆通国际":    "yuantongguoji",
	"韵达快递":    "yunda",
	"宅急送":     "zhaijisong",
	"中通快递":    "zhongtong",
	"EWE全球快递": "ewe",
	"全一快递":    "quanyikuaidi",
	"天天快递":    "tiantian",
	"顺心捷达":    "sxjdfreight",
	"DHL-中国件": "dhl",
	"TNT":     "tnt",
	"其它快递":    "other",
}

type config struct {
	Customer string `json:"customer"`
	Key      string `json:"key"`
}

func FastMail() *config {
	return &config{
		Customer: "6EBCB8B10BD7EA42585472144E4E7B43",
		Key:      "jcQbvIkP2598",
	}
}
func (s *config) GetKd100Flags(flags string) string {
	return kd100Flags[flags]
}
func (s *config) Query(c *gin.Context, param map[string]any, sendUrl string) (string, error) {
	// 配置参数
	key := s.Key           // 客户授权key
	customer := s.Customer // 查询公司编号
	// JSON 序列化 param
	paramJson, _ := gjson.Marshal(param)
	// 计算签名
	encrypt, err := gmd5.Encrypt(string(paramJson) + key + customer)
	if err != nil {
		return "", err
	}
	sign := gconv.String(encrypt)

	// 构造 post_data 并 URL 编码
	postData := url.Values{}
	postData.Set("customer", customer)
	postData.Set("param", string(paramJson))
	postData.Set("sign", strings.ToUpper(sign))
	// 发起 POST 请求
	client := g.Client()
	resp, err := client.Post(c, sendUrl, postData.Encode())
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return gconv.String(body), err
}

func (s *config) Poll(param map[string]any, sendUrl string) (string, error) {
	// JSON 序列化 param
	paramJson, _ := gjson.Marshal(param)
	// 构造 post_data 并 URL 编码
	postData := url.Values{}
	postData.Set("schema", "json")
	postData.Set("param", string(paramJson))
	// 请求地址
	background := context.Background()
	// 发起 POST 请求
	client := g.Client()
	resp, err := client.Post(background, sendUrl, postData.Encode())
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return gconv.String(body), err
}
